/**
 * Project: encrypt-test
 * Created: 2016年12月9日
 * Copyright ©2011-2016 gopay Information Technology Co., LTD All Rights Reserved
**/
package com.gopay.common.util.cbrmb.xml;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** 
 * @ClassName: JaxbXmlUtils 
 * @author junjie.ge 
 * @date 2016年12月9日 下午5:54:33  
 */

public class CbrmbXmlUtils {
    private static final Logger LOG = LoggerFactory.getLogger(CbrmbXmlUtils.class);
    private static CbrmbXmlUtils instance;
    private CbrmbXmlUtils() {}
    public static CbrmbXmlUtils getInstance() {
        if (instance == null) {
            synchronized (CbrmbXmlUtils.class) {
                if (instance == null) {
                    instance = new CbrmbXmlUtils();
                }
            }
        }
        return instance;
    }
    
    public String toXml(Object boundObj, Class<?>... classes) {
        StringWriter writer = null;
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(classes);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            writer = new StringWriter();
            marshaller.marshal(boundObj, writer);
            result = writer.toString();
        } catch (JAXBException e) {
            LOG.error(e.getMessage(), new IllegalStateException(e));
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    // do nothing......
                }
            }
        }
        return result;
    }
    
    public Object toBean(String xml, Class<?> beanClasses) {
        Object result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(beanClasses);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader reader = new StringReader(xml);
            result = unmarshaller.unmarshal(reader);
        } catch (JAXBException e) {
            LOG.error(e.getMessage(), new IllegalStateException(e));
        }
        return result;
    }
}
